/*
 * ses_buzzer.c
 *
 *  Created on: Jun 28, 2013
 *      Author: ABBOUD
 */

/* INCLUDES ******************************************************************/

# include "ses_buzzer.h"

/* Variables ******************************************************************/
uint16_t buzz_time_ON, buzz_time_OFF;	//Buzzer Time length for ON and OFF alarm


/* FUNCTION Declaration *******************************************************/
void buzz_Periodic_OFF();
void buzz_Periodic_ON();

/* FUNCTION DEFINITION *******************************************************/


/*
 * initializes Buzzer
 */
void buzz_Init(void) {
	TCCR0A |= (1<<COM0B1)|(0<<COM0B0)|(1<<WGM01)|(1<<WGM00);	//Fast PWM, TOP=0xff,non-inverted PWM.
	TCCR0A &=~(1<<COM0B0);
	TCCR0B &= ~((1<<WGM02)|(1<<CS00)|(1<<CS01));
	TCCR0B |= (1<<CS02);										//prescale 256.fpwm=2450Hz.
	TCNT0 = 0;           										// Reset TCNT0
    OCR0B=OCR0B_BUZZ;  											//50% duty-cycle
}


/*
 * activate Buzzer
 */
void buzz_Act(void){
	DDR (BUZZ_PORT) |= (1 << BUZZ_PIN);  						//set as OUTPUT channel
	BUZZ_PORT|= (1<<BUZZ_PIN);
}

/*
 * deactivate buzzer
 */
void buzz_Deact(void){
	DDR (BUZZ_PORT) &= ~(1 << BUZZ_PIN);  						//set as INPUT channel
	scheduler_remove(buzz_Periodic_OFF);
	scheduler_remove(buzz_Periodic_ON);
}



/*
 * Buzzer Alarm Period
 */
void buzz_Act_Period(uint16_t time) {
	buzz_Act();
	scheduler_add(buzz_Deact, time, 0);
}

/*
 * Buzzer Toggle periodic OFF & ON
 */
void buzz_Periodic_OFF() {
	DDR (BUZZ_PORT) &= ~(1 << BUZZ_PIN); 						//Do NOT use @buzz_Deact()
	scheduler_add(buzz_Periodic_ON, buzz_time_OFF, 0);
}

void buzz_Periodic_ON() {
	buzz_Act();
	scheduler_add(buzz_Periodic_OFF, buzz_time_ON, 0);
}

/*
 * Alarm periodic Buzzer active forever
 */
void buzz_Act_Periodic_Forever(uint16_t time_ON, uint16_t time_OFF) {
	buzz_Deact();
	buzz_Act();
	buzz_time_ON = time_ON;
	buzz_time_OFF = time_OFF;
	scheduler_add(buzz_Periodic_OFF, time_ON, 0);
}

/*
 * Alarm periodic Buzzer for Time -total-
 */
void buzz_Act_Periodic(uint16_t time_ON, uint16_t time_OFF, uint16_t time_total) {
	buzz_Act_Periodic_Forever(time_ON, time_OFF);
	scheduler_add (buzz_Deact, time_total, 0);
}
/*
	//OR use com0b1=com0b0=0==>ordinary I/O mode..
	TCNT0 = 0;           // Reset TCNT0
	OCR0B = 0;           //always output low,PWM disable.
*/
